package day14;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public
class Client2 {
    static volatile boolean flag=true;
    public static
    void main(String[] args) throws IOException {
        Socket client=new Socket("192.168.26.100",9997);
        OutputStream os=client.getOutputStream();//向服务端写数据
        Scanner sc=new Scanner(System.in);//数据的来源
        //缺少一个向服务端读取数据 由于上面的读写和监听服务器的数据是相互独立的 所以需要开一个线程来读取数据
        new Thread(new ClientListener(client)).start();
        System.out.println("输入姓名");
        String name=sc.nextLine();
        while (true){
            System.out.println("请输入要发送的数据：(esc退出)");
            String msg=sc.nextLine();

            if(msg!=null){
                if(msg.contains("esc")){
                    os.write((name+"说：退出聊天室esc\n").getBytes());
                    flag=false;
                    break;
                }else {
                    os.write((name+"说："+msg+"\n").getBytes());
                }
            }
        }
        os.close();
        client.close();
    }
}
class ClientListener implements Runnable{
     Socket client;
    public ClientListener(Socket client){
        this.client=client;
    }
    @Override
    public void run() {
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
            while (Client2.flag){
                String msg=br.readLine();
                if(msg!=null){
                    System.out.println(msg);
                }
            }
        } catch (Exception e) {
        }
    }
}